package dispatcher;

import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;
import java.util.Properties;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import services.CompanyService;
import services.NotificationsService;
import services.PollService;
import utils.MyBase64;
import utils.Utils;
import business.PollValue;
import exceptions.ExDBException;

public class SavePoll extends HttpServlet{
	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;
	
	public SavePoll() 
	{
		
	}

	protected void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		
		Properties msge = Utils.getProperties("resource/messages_es.properties");
		HttpSession session = request.getSession(true);
		Object sessionUserID = session.getAttribute("userID");
		Object sessionCompanyStatus = session.getAttribute("companyStatus");
		PollService pollService = new PollService();
		CompanyService companyService = new CompanyService();
		NotificationsService notificationsService = new NotificationsService();
		
		String templateFilePath = this.getServletContext().getRealPath(String.valueOf(File.separatorChar)) + "mail.html";
		
		if(sessionUserID == null || sessionUserID.toString().trim().length() == 0)
		{
			response.sendRedirect("./login?option=" + MyBase64.encode(Login.NO_SESSION.getBytes()));
		}
		else
		{
			response.setContentType("text/xml;charset=ISO-8859-1");
			request.setCharacterEncoding("ISO-8859-1");
			String rejectComments = request.getParameter("rejectCommentsTA");
			String campaignCompanyIDStr = request.getParameter("companyCampaignID");
			String encuestaIDStr = request.getParameter("pollID");
			String localStr = request.getParameter("localID");
			String statusStr = request.getParameter("statusID");
			Long userID = null;
			Long pollID = null;
			Long statusID = null;
			Long pollCompanyID = null;
			Long campaignCompanyID = null;
			Long companyStatusID = (Long) sessionCompanyStatus;
			Long companyStatusIDUpdate = null;
			Long localID = null;
			String params = null;
			if (encuestaIDStr != null
					&& encuestaIDStr.trim().length() > 0 && campaignCompanyIDStr != null
					&& campaignCompanyIDStr.trim().length() > 0 && localStr != null
					&& localStr.trim().length() > 0 && statusStr != null
					&& statusStr.trim().length() > 0) {
				try {
					pollID = Long.valueOf(encuestaIDStr);
					statusID = Long.valueOf(statusStr);
					campaignCompanyID = Long.valueOf(campaignCompanyIDStr);
					localID = Long.valueOf(localStr);
					userID = Long.valueOf(sessionUserID.toString());
					params = MyBase64.encode(String.valueOf(campaignCompanyIDStr + "|" + pollID + "|" + localID).getBytes());
					
				} catch (Exception e) {
					// TODO: ERROR AL CONVERTIR POLL Y COMPANY A LONG
				}
				List<PollValue> listaValoresEncuesta = pollService
				.getPollValues(pollID, campaignCompanyID,localID);
				pollCompanyID = listaValoresEncuesta.get(0).getCompanyPoll().getId();
				
				if(companyStatusID == PollService.POLL_STATUS_NEW)
				{
					companyStatusIDUpdate = PollService.POLL_STATUS_EDITED;
				}
				
				for(PollValue valorEncuesta : listaValoresEncuesta)
				{
					String attName = valorEncuesta.getPollDefinition().getCode();
					String value = request.getParameter(attName);
										
					if(value != null)
					{
						valorEncuesta.setValue(value.replace(".", "").replace(",", "."));	
					}					
				}
				String page = null;
				try {
					if(statusID == PollService.FORM_STATUS_APPROVED)
					{
						try {
							pollService.updateFormStatus(pollCompanyID,statusID,userID);
							if(pollService.checkIsStartRevision(campaignCompanyID))
							{
								notificationsService.sendNotificationStatusChange(templateFilePath, companyService.getCompanyCampaign(campaignCompanyID), pollService.getPollStatusByID(PollService.POLL_STATUS_REVIEW));
							}
							page = Utils.getAjaxParams(Utils.MESSAGE_TYPE_SUCCESS,
									msge.getProperty("savePoll.approved.succesfully"),Integer.valueOf(statusStr),params,0L);
						} catch (Exception e) {
							page = Utils.getAjaxParams(Utils.MESSAGE_TYPE_ERROR,
									e.getMessage());
						}
					}
					else if(statusID == PollService.FORM_STATUS_REJECTED)
					{
						try {
							pollService.updateFormStatus(pollCompanyID,statusID,userID,rejectComments);
							if(pollService.checkIsStartRevision(campaignCompanyID))
							{
								notificationsService.sendNotificationStatusChange(templateFilePath, companyService.getCompanyCampaign(campaignCompanyID), pollService.getPollStatusByID(PollService.POLL_STATUS_REVIEW));
							}
							page = Utils.getAjaxParams(Utils.MESSAGE_TYPE_SUCCESS,
									msge.getProperty("savePoll.rejected.succesfully"),Integer.valueOf(statusStr),params,0L);
						} catch (Exception e) {
							page = Utils.getAjaxParams(Utils.MESSAGE_TYPE_ERROR,
									e.getMessage());
						}
					}
					else
					{
						pollService.savePollValues(listaValoresEncuesta,userID,statusID);					
						try {
							if(pollID == PollService.POLL_L_ID)
							{
								pollService.execSum(campaignCompanyID);	
								pollService.execSumVariables(campaignCompanyID);
							}
							else if(pollID == PollService.POLL_E_ID)
							{
								pollService.execSumVariables(campaignCompanyID);	
							}
							page = Utils.getAjaxParams(Utils.MESSAGE_TYPE_SUCCESS,
									msge.getProperty("savePoll.save.succesfully"),Integer.valueOf(statusStr),params,companyStatusIDUpdate);
							
						} catch (Exception e) {
							page = Utils.getAjaxParams(Utils.MESSAGE_TYPE_WARNING,
									e.getMessage(),Integer.valueOf(statusStr),params,0L);
						}
					}
				} catch (ExDBException e) {
					page = Utils.getAjaxParams(Utils.MESSAGE_TYPE_ERROR,
					e.getMessage());
				}
				PrintWriter out = response.getWriter();
				out.print(page);
//				response.sendRedirect(page);
			}
		}
	}
	
	protected void doGet(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		
		doPost(req, resp);
	}
}
